package com.example.okhttp3;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Login extends AppCompatActivity {
    EditText mEtUserName,mEtPassWord;
    Button mBtnEnter;
    private static final String TAG = "Login";
    String name,password1;
    int status;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        initView();
        initEvent();
    }

    private void initEvent() {
        mBtnEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = String.valueOf(mEtUserName.getText());
                String password = String.valueOf(mEtPassWord.getText());

                OkHttpClient client = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("username", username)
                        .add("password", password)
                        .build();
                 Request request = new Request.Builder()
                        .url(" https://anli-wechat.boruiman.com/api/UserServer/user_login")
                        .post(body)
                        .build();
                 Call call = client.newCall(request);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Response request1 = call.execute();
                            String data = request1.body().string();
                            JSONObject jsonObject = new JSONObject(data);
                            name = jsonObject.optString("username");
                            password1 = jsonObject.optString("password");
                            status = jsonObject.optInt("status");
                            Log.e(TAG,"run"+data);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    private void initView() {
        mEtUserName = findViewById(R.id.et_username);
        mEtPassWord = findViewById(R.id.et_password);
        mBtnEnter = findViewById(R.id.btn_enter);
    }
}
